package com.group.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group.mapper.UserAccountMapper;
import com.group.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pojo.dto.UserRecord;
import pojo.entity.Order;

import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
public class UserAccountServiceImpl implements UserAccountService {
    @Autowired
    private UserAccountMapper accountMapper;

    @Override
    public double findBalanceByUserId(Long userId) {
        return accountMapper.selectByUserId(userId);
    }

    @Override
    public Integer addBalanceAndOrder(Order order) {
        Long userId = order.getUserId();
        double money = order.getMoney();
        order.setOrderNumber(System.currentTimeMillis()); //生成订单号

        //更新用户余额
        double oldBalance = accountMapper.selectByUserId(userId);
        int update = accountMapper.updateUserBalance(userId, money + oldBalance);
        //添加订单
        int insert = accountMapper.insertOrder(order);
        // 成功，返回业务数据 1
        if (update != 0 && insert != 0) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public Integer updateUserBalance(Long userId, Double money) {
        return accountMapper.updateUserBalance(userId, money);
    }

    @Override
    public PageInfo findUserRecordPage(Integer currentPage, Integer pageSize, Long userId) {
        PageHelper.startPage(currentPage, pageSize); //会对下面第一个查询结果进行分页
        List<UserRecord> list = accountMapper.selectAllUserRecord(userId);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }


}
